package com.client;

import com.domain.LoginForm;
import com.struct.Request;
import com.struct.RequestHeader;
import com.struct.Response;
import com.struct.ResultCode;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.msgpack.MessagePack;

import java.util.Date;

/**
 * Created by Greg.chen on 2016-03-20.
 */
public class ClientHandler extends ChannelHandlerAdapter {

    private SwingClient swingClient;

    public ClientHandler(SwingClient swingClient) {
        this.swingClient = swingClient;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        String date = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        swingClient.textArea1.append(date + " 连接服务端成功!" + "\n");

    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Response response = (Response) msg;
        // 如果是握手请求消息，处理，其它消息透传
        if (response != null && response.getHeader() != null) {
            String date = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");

            String uri = response.getHeader().getUri();



            if("/login".equalsIgnoreCase(uri)){
                MessagePack messagePack = new MessagePack();

                if(response.getHeader().getStateCode() != ResultCode.SUCCESS){

                    swingClient.textArea1.append(date + " 登录失败, 原因:" + messagePack.read(response.getBodyBytes(), String.class) + "\n");
                }
                else{
                    swingClient.textArea1.append(date + " " + messagePack.read(response.getBodyBytes(), String.class) + "\n");
                }
            }

        }
        else{
            ctx.fireChannelRead(msg);
        }
    }





}
